package com.apex.lottery.service.strategy.activitystatus.impl;

import com.apex.lottery.common.errorcode.ServiceErrorCodeConstants;
import com.apex.lottery.common.exception.ServiceException;
import com.apex.lottery.service.ActivityService;
import com.apex.lottery.service.strategy.activitystatus.ActivityStatusManager;
import com.apex.lottery.service.strategy.activitystatus.operater.AbstractActivityOperator;
import com.apex.lottery.service.dto.ConvertActivityStatusDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.spel.ast.Operator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @ClassName ActivityStatusManagerImpl
 * @Description
 * @Author ZJX
 * @Date 2025/4/21 12:01
 * @Version 1.0
 **/
@Service
public class ActivityStatusManagerImpl implements ActivityStatusManager {
    @Autowired
    private ActivityService activityService;

    @Autowired
    private final Map<String, AbstractActivityOperator> operatorMap = new HashMap<>();

    private static final Logger logger = LoggerFactory.getLogger(ActivityStatusManagerImpl.class);

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handlerEvent(ConvertActivityStatusDTO convertActivityStatusDTO) {
        if (CollectionUtils.isEmpty(operatorMap)) {
            logger.warn("operatorMap 为空！");
            return;
        }

        Map<String, AbstractActivityOperator> curMap = new HashMap<>(operatorMap);
        Boolean update = false;
//        先处理人员 奖品
        update = processConvertStatus(convertActivityStatusDTO,curMap,1);
//        后处理活动
        update = processConvertStatus(convertActivityStatusDTO,curMap,2) || update;

//        更新缓存
        if (update){
            activityService.cacheActivity(convertActivityStatusDTO.getActivityId());
        }
    }

    /**
     * 回滚处理活动相关状态
     * @param convertActivityStatusDTO
     */
    @Override
    public void rollbackHandlerEvent(ConvertActivityStatusDTO convertActivityStatusDTO) {
        // operatorMap：活动、奖品、人员
        for (AbstractActivityOperator operator : operatorMap.values()) {
            operator.convert(convertActivityStatusDTO);
        }

//        更新缓存
        activityService.cacheActivity(convertActivityStatusDTO.getActivityId());
    }

    /**
     * 扭转状态
     *
     * @param convertActivityStatusDTO
     * @param curMap
     * @param sequence
     * @return
     */
    private Boolean processConvertStatus(ConvertActivityStatusDTO convertActivityStatusDTO,
                                         Map<String, AbstractActivityOperator> curMap,
                                         int sequence) {
        Boolean update = false;
        // 遍历currMap
        Iterator<Map.Entry<String, AbstractActivityOperator>> iterator = curMap.entrySet().iterator();
        while (iterator.hasNext()) {
            AbstractActivityOperator operator = iterator.next().getValue();
            // Operator 是否需要转换
            if (operator.sequence() != sequence
                    || !operator.needConvert(convertActivityStatusDTO)) {
                continue;
            }

            // 需要转换：转换
            if (!operator.convert(convertActivityStatusDTO)) {
                logger.error("{}状态转换失败！", operator.getClass().getName());
                throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_STATUS_CONVERT_ERROR);
            }

            // currMap 删除当前 Operator
            iterator.remove();
            update = true;
        }
        // 返回
        return update;
    }

}
